<template>
    <div class="app-container">
        <el-form :inline="true" :model="queryParams" ref="queryForm">
            <el-form-item label="货品名称" prop="goodsName">
                <el-input
                        v-model="queryParams.goodsName"
                        placeholder="请输入货品名称"
                        clearable
                        size="small"
                />
            </el-form-item>
            <el-form-item label="货品编码" prop="goodsId">
                <el-input
                        v-model="queryParams.goodsId"
                        placeholder="请输入货品编码"
                        clearable
                        size="small"
                />
            </el-form-item>
            <el-form-item label="货品大类" prop="goodsCategory">
                <el-select v-model="queryParams.goodsCategory" placeholder="货品大类"  clearable size="small">
                    <el-option
                            v-for="dict in goodsCategoryOptions"
                            :key="dict.dictValue"
                            :label="dict.dictLabel"
                            :value="dict.dictValue"
                    />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetGoodsForm">重置</el-button>
            </el-form-item>
        </el-form>

        <el-table v-loading="loading" border :data="goodsList">
            <el-table-column label="货品编码" prop="goodsId" width="110"/>
            <el-table-column label="货品名称" prop="goodsName" :show-overflow-tooltip="true"/>
            <el-table-column label="货品大类" prop="goodsCategory" :formatter="goodsCategoryFormat"
                             :show-overflow-tooltip="true"/>
            <el-table-column label="货品小类" prop="goodsType" :show-overflow-tooltip="true"/>
            <el-table-column label="计量单位" prop="goodsMeasurementUnit" align="center" width="80"/>
            <el-table-column label="货品属性" align="center" width="100">
                <template slot-scope="scope">
                    <el-tooltip class="item" effect="dark" placement="top-start">
                        <div slot="content">
                            <p v-for="goodsAttribute in scope.row.goodsAttributeList">
                                {{goodsAttribute.attrName}}&nbsp;:&nbsp;{{goodsAttribute.attrValue}}
                            </p>
                        </div>
                        <el-button>查看</el-button>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column label="货品描述" prop="goodsDes" :show-overflow-tooltip="true"/>
            <el-table-column label="操作时间" align="center" prop="updateTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.updateTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-edit"
                            @click="handleUpdate(scope.row)"
                            v-hasPermi="['goods:modifyGoods']"
                    >修改
                    </el-button>
                    <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-delete"
                            @click="handleDelete(scope.row)"
                            v-hasPermi="['goods:delGoods']"
                    >删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination
                v-show="total>0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
        />
        <!-- 修改货品信息对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
            <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="130px">
                <el-form-item label="货品名称" prop="goodsName">
                    <el-input v-model="formData.goodsName" placeholder="请输入货品名称" show-word-limit clearable
                              :style="{width: '100%'}"></el-input>
                </el-form-item>
                <el-form-item label="货品大类" prop="goodsCategory">
                    <el-radio-group v-model="formData.goodsCategory" @change="changeGoodsType" size="medium">
                        <el-radio v-for="(item, index) in goodsCategoryOptions" :key="index" :label="item.dictValue">
                            {{item.dictLabel}}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="货品小类" prop="goodsType">
                    <el-select v-model="formData.goodsType" size="medium">
                        <el-option
                                v-for="item in goodsTypeOptions"
                                :key="item.dictValue"
                                :label="item.dictLabel"
                                :value="item.dictValue"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="货品估价" prop="goodsPrice">
                    <el-input v-model="formData.goodsPrice" placeholder="请输入货品的市场估价" show-word-limit clearable
                              :style="{width: '100%'}">
                        <template slot="append">元</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="计量单位" prop="goodsMeasurementUnit">
                    <el-input v-model="formData.goodsMeasurementUnit" placeholder="请输入货品的计量单位" show-word-limit clearable
                              :style="{width: '100%'}"></el-input>
                </el-form-item>
                <el-form-item label="预警阀值" prop="waringNumber">
                    <el-input-number v-model="formData.waringNumber" controls-position="right" :min="1"/>
                </el-form-item>
                <el-form-item label="条形码标识" prop="goodsBarCode">
                    <el-input v-model="formData.goodsBarCode" placeholder="请输入条形码标识" show-word-limit clearable
                              :style="{width: '100%'}"></el-input>
                </el-form-item>
                <el-form-item label="二维码标识" prop="goodsQrCode">
                    <el-input v-model="formData.goodsQrCode" placeholder="请输入二维码标识" show-word-limit clearable
                              :style="{width: '100%'}"></el-input>
                </el-form-item>
                <el-form-item label="货品描述" prop="goodsDes">
                    <el-input v-model="formData.goodsDes" type="textarea" placeholder="请输入货品描述信息"
                              show-word-limit
                              :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
                </el-form-item>
                <el-form-item v-for="(item,index) in formData.goodsAttributeList"
                              :label="'商品属性 ' + (index+1)"
                              :key="index"
                              :prop="'goodsAttributeList.' + index + '.attrName'"
                              :rules="{
                                    required: true, message: '货品属性不能为空', trigger: 'blur'
                                    }"
                >
                    <el-input v-model="item.attrName" class="inputWidth" placeholder="请输入货品属性名" clearable></el-input>
                    <el-input v-model="item.attrValue" class="inputWidth" placeholder="请输入货品属性值描述" clearable></el-input>
                    <el-button v-if="index == formData.goodsAttributeList.length-1" @click="addItem" type="success"
                               icon="el-icon-plus" circle size="mini"></el-button>
                    <el-button @click="delItem(index)" type="danger" icon="el-icon-delete" circle
                               size="mini"></el-button>
                </el-form-item>
                <el-form-item label="货品图片">
                    <el-upload ref="imgaeRef"
                               :file-list="imageFileList"
                               :auto-upload="false"
                               action=""
                               :limit="5"
                               :on-exceed="OnImageExceed"
                               :before-upload="imageBeforeUpload"
                               :on-remove="imageRemove"
                               :on-preview="handlePreview"
                               list-type="picture-card"
                               accept="image/*">
                        <i class="el-icon-plus"></i>
                        <div slot="tip" class="el-upload__tip">只能上传不超过 5MB 的image/*文件，最多上传5张图片</div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {listGoods,modifyGoods,delGoods} from "@/api/goods/goods.js";
    import {queryDocByBusiId, downloadDoc} from "@/api/document/document.js";

    export default {
        name: "listGoods",
        components: {},
        data() {
            return {
                // 公司数据
                goodsList: [],
                // 总条数
                total: 0,
                // 遮罩层
                loading: true,
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                // 货品大类数据字典
                goodsCategoryOptions: [],
                // 货品小类数据字典
                goodsTypeOptions: [],
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    goodsName: undefined,
                    goodsCategory: undefined,
                    goodsId: undefined
                },
                // 表单参数
                formData: {
                    goodsAttributeList: []
                },
                realFormData: new FormData(),
                // 表单校验
                rules: {
                    goodsName: [{
                        required: true,
                        message: '请输入货品名称',
                        trigger: 'blur'
                    }],
                    goodsPrice: [{
                        required: true,
                        message: '请输入货品市场估价',
                        trigger: 'blur'
                    }],
                    goodsMeasurementUnit: [{
                        required: true,
                        message: '请输入计量单位',
                        trigger: 'blur'
                    }],
                    waringNumber: [{
                        required: true,
                        message: '请输入库存不足预警阀值',
                        trigger: 'change'
                    }]
                },
                imageFileList: [],
                removeFileList: [],
                docOpen: false,
                documentList: [],
                /*附件添加列表*/
                appendixFilefileList: [],
                openCompanyDocInfo: null,
                appendixFileForm: new FormData()
            };
        },
        created() {
            this.getList();
            let app = this;
            app.getDicts("goods_info_goods_category").then(response => {
                app.goodsCategoryOptions = response.data;
                var dataList = response.data;
                if(dataList != null && dataList.length>0){
                    app.formData.goodsCategory = dataList[0].dictValue;
                    app.getDicts("goods_category_" +  dataList[0].dictValue).then(response1 => {
                        app.goodsTypeOptions = response1.data;
                        app.formData.goodsType = response1.data[0].dictValue;
                    });
                }
            });
        },
        methods: {
            /** 查询按钮操作 */
            handleQuery() {
                this.getList();
            },
            /** 查询货品列表 */
            getList() {
                this.loading = true;
                listGoods(this.queryParams).then(
                    response => {
                        this.goodsList = response.rows;
                        this.total = response.total;
                        this.loading = false;
                    }
                );
            },
            changeGoodsType(){
                let app = this;
                app.getDicts("goods_category_" +  this.formData.goodsCategory).then(response1 => {
                    app.goodsTypeOptions = response1.data;
                    app.formData.goodsType = response1.data[0].dictValue;
                });
            },
            /** 修改按钮操作 */
            handleUpdate(row) {
                //将现有的公司logo图片展示
                let data = {
                    busiId: row.goodsId,
                    docType: "货品图片"
                };
                queryDocByBusiId(data).then(response => {
                    if (response.data != null && response.data.length > 0) {
                        let docementObj = response.data;

                        let logoWebObj = [];
                        if(docementObj != null && docementObj.length>0){
                            for(var i=0; i<docementObj.length; i++){
                                logoWebObj.push({
                                    name: docementObj[i].docName,
                                    url: process.env.VUE_APP_BASE_API + docementObj[i].docUrl
                                });
                            }
                        }
                        this.imageFileList = logoWebObj;
                    }
                });
                //将列表中的选中对象信息拷贝到修改界面的对象中去,assign方法很重要，防止取消之后影响分页表格数据
                this.formData = Object.assign({}, row);
                this.open = true;
                this.title = "修改货品信息";
            },
            // 取消按钮
            cancel() {
                this.open = false;
            },
            /** 提交按钮 */
            submitForm: function () {
                this.$refs["elForm"].validate(valid => {
                    if (valid) {
                        let app = this;
                        setTimeout(function () {
                            //上传函数，如果把提交函数用在http-request钩子中，
                            // fileList多长就执行请求多少次接口，依旧是无法做到只请求一次上传多文件
                            //  用FormData存放上传文件
                            app.realFormData.append("goodsId",app.formData.goodsId);
                            app.realFormData.append("goodsName",app.formData.goodsName);
                            app.realFormData.append("goodsCategory",app.formData.goodsCategory);
                            app.realFormData.append("goodsType",app.formData.goodsType);
                            app.realFormData.append("goodsPrice",app.formData.goodsPrice);
                            app.realFormData.append("goodsMeasurementUnit",app.formData.goodsMeasurementUnit);
                            app.realFormData.append("waringNumber",app.formData.waringNumber);
                            app.realFormData.append("goodsBarCode",app.formData.goodsBarCode);
                            app.realFormData.append("goodsQrCode",app.formData.goodsQrCode);
                            app.realFormData.append("goodsDes",app.formData.goodsDes);
                            app.realFormData.append("goodsAttrListJson",JSON.stringify(app.formData.goodsAttributeList));
                            app.realFormData.append("removeFileListJson",JSON.stringify(app.removeFileList));
                            //进行elementUi上传组件的提交触发
                            app.$refs['imgaeRef'].submit();

                            modifyGoods(app.realFormData).then(response => {
                                if (response.code === 200) {
                                    app.msgSuccess("修改货品信息成功！");
                                    app.getList();
                                    app.open = false;
                                } else {
                                    app.msgError(response.msg);
                                }
                            });
                            app.realFormData = new FormData();
                        }, 1000);
                    }
                });
            },
            imageBeforeUpload(file) {
                let isRightSize = file.size / 1024 / 1024 < 5
                if (!isRightSize) {
                    this.$message.error('文件大小超过 5MB')
                }
                let isAccept = new RegExp('image/*').test(file.type)
                if (!isAccept) {
                    this.$message.error('应该选择image/*类型的文件')
                }

                if (isRightSize && isAccept) {
                    this.realFormData.append('imageFile', file);
                    return false;
                } else {
                    return false;
                }
            },
            OnImageExceed(file, fileList) {
                this.$message.error(`只能上传5张图片!`);
            },
            //文件移除时的钩子，添加删除信息
            imageRemove(file, fileList){
                if(file.status == "success"){
                    var imageUrl = file.url.replace(process.env.VUE_APP_BASE_API,"");
                    var docData = {
                        docName: file.name,
                        docUrl: imageUrl
                    }
                    this.removeFileList.push(docData);
                }
            },
            handlePreview(row){
                this.$confirm('确定下载该图片？', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(response => {
                    var imageUrl = row.url.replace(process.env.VUE_APP_BASE_API+"/profile","");
                    var docData = {
                        docName: row.name,
                        docUrl: imageUrl
                    }
                    downloadDoc(docData);
                })
            },
            /** 删除按钮操作 */
            handleDelete(row) {
                let app = this;
                this.$confirm('是否确定删除名称为"' + row.goodsName + '"的货品?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function () {
                    delGoods(row).then(response => {
                        if (response.code === 200) {
                            app.msgSuccess("删除成功");
                            app.getList();
                        } else {
                            app.msgError(response.msg);
                        }
                    });
                });
            },
            goodsCategoryFormat(row) {
                return this.selectDictLabel(this.goodsCategoryOptions, row.goodsCategory);
            },
            addItem(){
                //添加一个空的数组元素
                this.formData.goodsAttributeList.push({attrName: '',attrValue: ''});
            },
            delItem(index){
                //移除指定索引的数组元素
                this.formData.goodsAttributeList.splice(index,1);
            },
            resetGoodsForm(){
                this.resetForm("queryForm");
            }
        }
    };
</script>
<style>
    .inputWidth{
        width: 40%;
        margin-right: 15px;
    }
</style>

